package com.vectorimage.util;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import com.vectorimage.entity.Face;
import com.vectorimage.entity.RGB;
import com.vectorimage.entity.ReadFaces;

/**
 * 默认图片信息解析器
 * 
 * @author bluishoul@gmail.com
 */
public class DefaultFacesReader implements ReadFaces{

	private String		path;

	private int[]		pixels;

	private List<RGB>	rgb;

	private List<Float>	grey;

	private int			width	= 0;

	private int			height	= 0;

	public DefaultFacesReader(String path) throws Throwable{
		this.path = (path == null || "".equals(path)) ? this.path : path;
		service();
	}

	public DefaultFacesReader() throws Throwable{
		service();
	}

	@Override
	public void setImagePath(String path){
		this.path = path;
	}

	@Override
	public String getImagePath(){
		return path;
	}

	@Override
	public List<RGB> getRGB() throws Throwable{
		if(rgb == null) throw new Throwable("rgb is not initialed!");
		return rgb;
	}

	@Override
	public List<Float> getGrey() throws Throwable{
		if(grey == null) throw new Throwable("grey is not initialed!");
		return grey;
	}

	@Override
	public int getWidth() throws Throwable{
		if(width == 0) throw new Throwable("width is not initialed!");
		return width;
	}

	@Override
	public int getHeight() throws Throwable{
		if(height == 0) throw new Throwable("height is not initialed!");
		return height;
	}

	@Override
	public List<Float> service() throws Throwable{
		if(path == null) throw new Throwable("path null");
		File file = new File(path);
		if( !file.exists()) throw new Throwable("can't find the image:" + path);
		BufferedImage bufImg = ImageIO.read(file);
		height = bufImg.getHeight();
		width = bufImg.getWidth();
		pixels = new int[width * height];
		PixelGrabber pg = new PixelGrabber(bufImg, 0, 0, width, height, pixels, 0, width);
		pg.grabPixels();
		grey = new ArrayList<Float>(width * height);
		rgb = new ArrayList<RGB>(width * height);
		ColorModel cm = ColorModel.getRGBdefault();
		for(int i = 0; i < width * height; i++){
			int red = cm.getRed(pixels[i]);
			int green = cm.getGreen(pixels[i]);
			int blue = cm.getBlue(pixels[i]);
			float g = (float)(0.299 * red + 0.587 * green + 0.114 * blue);
			grey.add(g);
			RGB r = new RGB(red, green, blue);
			rgb.add(r);
		}
		return grey;
	}

	@Override
	public Face getFace() throws Throwable{
		if(rgb == null || grey == null || width == 0 || height == 0) throw new Throwable("rgb/grey/width/height is(are) not initialed!");
		return new Face(rgb, grey, width, height);
	}
}
